import 'dart:developer';

import 'package:FlutterDemo/common/commons.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';

/// MethodChannel: Flutter 与Native 端相互调用，调用后可以返回结果，可
/// 以Native 端主动调用，也可以Flutter 主动调用，属于双向通信。此方式为
/// 最常用的方式， Native 端调用需要在主线程中执行。
class PageMethodChannel extends StatelessWidget {
  const PageMethodChannel({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return _PageMethodChannel();
  }
}

class _PageMethodChannel extends StatefulWidget {
  const _PageMethodChannel({Key? key}) : super(key: key);

  @override
  _PageMethodChannelState createState() => _PageMethodChannelState();
}

class _PageMethodChannelState extends State<_PageMethodChannel> {
  var _resultMsg = "暂未收到回复";
  MethodChannel methodChannel = MethodChannel("com.example.zyflutter.action.zymc");

  @override
  void initState() {
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      child: Column(
        children: [
          buildCommonRaisedButton("调用原生方法", 20.0, () {
            log("调用原生方法");
            callTestMethod().then((value) {
              log("result: $value");
              setState(() {
                _resultMsg = value;
              });
            });
          }),
          Expanded(
              child: Container(
            width: double.infinity,
            child: Text(
              "$_resultMsg",
              textAlign: TextAlign.center,
            ),
          ))
        ],
      ),
    );
  }

  Future<String> callTestMethod() async {
    String s = await methodChannel.invokeMethod("request");
    log("message s = $s");
    return s;
  }
}
